﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Photon.SocketServer;
using Common;
using Common.Tools;
using Common.Model;

using MyGameServer.Manager;
using MyGameServer.Model;
using System.IO;
using System.Xml.Serialization;

namespace MyGameServer.Handler
{
    class ReadyHandler : BaseHandler
    {
        public ReadyHandler()
        {
            OpCode = OperationCode.Ready;
        }
        public override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters, ClientPeer peer)
        {
            int readyState = (int)DictTool.GetValue<byte, object>(operationRequest.Parameters, (byte)ParameterCode.Ready);
            Room room = Functions.GetRoomFromRoomListByPlayerId(MyGameServer.Instance.roomList, peer.uuid);
            CommonUser user = Functions.GetAvatarUser(room.playerList, peer.uuid);
            user.readyState = readyState;

            OperationResponse response = new OperationResponse(operationRequest.OperationCode);
            Dictionary<byte, object> data = new Dictionary<byte, object>();
            response.Parameters = data;
            peer.SendOperationResponse(response, sendParameters);
            
            //广播
            foreach (var ntfPeer in MyGameServer.Instance.peerList)
            {
                if (string.IsNullOrEmpty(ntfPeer.username) == false)
                {
                    bool isInRoom = Functions.IsPlayerInRoom(room, ntfPeer.uuid);
                    if (isInRoom)
                    {
                        EventData ed = new EventData((byte)EventCode.Ready);
                        Dictionary<byte, object> dataEvent = new Dictionary<byte, object>();
                        
                        CommonUser ntfUser = new CommonUser();
                        ntfUser.id = peer.uuid;
                        ntfUser.readyState = readyState;
                        string userString = Functions.ObjectToXmlString<CommonUser>(ntfUser);
                        dataEvent.Add((byte)ParameterCode.Ready, userString);
                        
                        ed.Parameters = dataEvent;
                        ntfPeer.SendEvent(ed, sendParameters);
                    }
                }
            }
        }
    }
}
